const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const db = require('../../data/db.json')

router.prefix('/api')

router.post('/login', async (ctx, next) => {
  try {
    const { username, password } = ctx.request.body
    const flag = db.users.some(
      (v) => v.username == username && v.password == password
    )
    const userInfo = db.users.find((v) => v.username == username)
    const token = jwt.sign({ ...userInfo, password: '' }, '2009A', {
      expiresIn: '24h',
    })
    if (flag) {
      ctx.body = {
        code: 0,
        msg: 'success',
        data: token,
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: error,
    }
  }
})

// 分页接口
router.get('/users', async (ctx, next) => {
  try {
    const { page = 1, size = 5 } = ctx.query
    const data = db.users.slice((page - 1) * size, page * size)
    ctx.body = {
      code: 0,
      msg: 'success',
      data: { data, total: db.users.length },
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: 'fail',
    }
  }
})

router.delete('/users/:id', async (ctx, next) => {
  console.log('ctx:', ctx.params)
  try {
    const { id } = ctx.params
    // splice => 下标删除
    const removeIndex = db.users.findIndex((v) => v.id == id)
    db.users.splice(removeIndex, 1)
    ctx.body = {
      code: 0,
      msg: 'success',
      data: db.users,
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: 'fail',
    }
  }
})
// 更新 put/patch
router.put('/users/:id', async (ctx, next) => {
  console.log('ctx:', ctx.params)
  try {
    const { id } = ctx.params
    const userInfo = ctx.request.body
    console.log('userInfo:', userInfo)
    // splice => 下标删除
    const index = db.users.findIndex((v) => v.id == id)
    db.users.splice(index, 1, userInfo)
    console.log('db:', db.users)
    ctx.body = {
      code: 0,
      msg: 'success',
      data: db.users,
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: 'fail',
    }
  }
})

module.exports = router
